package org.theSeed.springBase.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.theSeed.base.exp.ServiceExp;
import org.theSeed.springBase.contract.ThreadCache;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ThreadCacheHolder {
    @Autowired(required = false)
    private List<ThreadCache> threadCacheList;

    @PostConstruct
    public void init(){
        if (CollectionUtil.isNotEmpty(threadCacheList)){
            for (ThreadCache threadCache : threadCacheList) {
                ThreadCache has = threadCacheMap.put(threadCache.handlerType(), threadCache);
                if (ObjectUtil.isNotNull(has)){
                    throw new ServiceExp(threadCache.handlerType()+"该类型缓存已存在");
                }
            }
        }
    }

    private Map<String,ThreadCache> threadCacheMap = new HashMap<>();

    /**
     * 获取数据
     * @param type
     * @return
     * @param <T>
     */
    public <T> T getData(String type){
        return (T)(getThreadCache(type).getData());
    }

    /**
     * 设置数据
     * @param data
     * @param type
     * @param <T>
     */
    public <T> void setData(T data,String type){
        getThreadCache(type).setData(data);
    }

    /**
     * 清除数据
     * @param type
     * @param <T>
     */
    public <T> void clear(String type){
        getThreadCache(type).clear();
    }

    /**
     * 获取指定实现
     * @param type
     * @return
     * @param <T>
     */
    public <T> ThreadCache<T> getThreadCache(String type){
        ThreadCache threadCache = threadCacheMap.get(type);
        if (ObjectUtil.isNull(threadCache)){
            throw new ServiceExp("线程缓存器不存在");
        }
        return threadCache;
    }
}
